package com.yungu.swift.socket.communication.server.handler.strategy;

import com.alibaba.dubbo.rpc.RpcContext;
import com.google.gson.Gson;
import com.yungu.swift.autoconfig.redis.RedisCacheService;
import com.yungu.swift.base.SpringContextHolder;
import com.yungu.swift.socket.communication.message.LoginMessage;
import com.yungu.swift.socket.communication.message.LoginResponseMessage;
import com.yungu.swift.socket.component.ChannelKeeper;
import com.yungu.swift.socket.component.LoginUserUtils;
import com.yungu.swift.socket.push.model.PushContent;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

/**
 * 登陆响应
 *
 * @author : cuixiuyin
 * @date : 2019/8/30
 */
@Slf4j
public class LoginHandler implements MessageHandler {


    @Override
    public void handler(ChannelHandlerContext channelHandlerContext, String text) {
        Gson gson = new Gson();
        LoginMessage loginMessage = gson.fromJson(text, LoginMessage.class);
        //通过dubbo调用登录业务处理
        if (LoginUserUtils.loginUser(loginMessage)) {
            log.info("登录报文创建推送通道 netty client login success:uuid-->{}", loginMessage.getClientUuid());
            //登录时作移除通道动作 防止情况下与原设备保持连接
            ChannelKeeper.removeByUuid(loginMessage.getClientUuid());
            //登录成功，保存连接到连接容器
            ChannelKeeper.add(loginMessage.getClientUuid(), channelHandlerContext.channel());
            //Zerrion 2019-05-12 加入长连接集群代码,客户端连接长连接服务器某节点时将客户端ID及节点IP端口信息保存到缓存中备用
            String dubboProviderIp = RpcContext.getContext().getLocalHost();
            RedisCacheService redisCacheService = SpringContextHolder.getBean(RedisCacheService.class);
            redisCacheService.set(PushContent.SOCKET_CLUSTER_PREFIX + loginMessage.getClientUuid(), dubboProviderIp + ":" + 20997);
            //响应客户端
            LoginResponseMessage loginResponse = new LoginResponseMessage(true, "登录成功");

            loginResponse.setClientUuid(loginMessage.getClientUuid());
            channelHandlerContext.channel().writeAndFlush(new TextWebSocketFrame(gson.toJson(loginResponse)));
        } else {
            log.info("netty client login fail:uuid-->{},token-->{}", loginMessage.getClientUuid(), loginMessage.getToken());
            LoginResponseMessage loginResponse = new LoginResponseMessage(false, "登录失败,请确认ID和令牌是否合法");
            channelHandlerContext.channel().writeAndFlush(new TextWebSocketFrame(gson.toJson(loginResponse)));
        }
    }
}
